package com.example.jobseek;

import java.sql.Blob;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.google.gson.Gson;

import domain.PersonaVO;
import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Registro extends ActionBarActivity {

	TextView header;
	TextView tRut;
	TextView tPass;
	TextView tNombre;
	TextView tApellido;
	TextView tCiudad;
	
	EditText rut;
	EditText pass;
	EditText nombre;
	EditText apellido;
	EditText ciudad;
	
	Button registrar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_registro);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		
		header = (TextView)findViewById(R.id.txtheader);
		tRut = (TextView)findViewById(R.id.Rut);
		tPass = (TextView)findViewById(R.id.Password);
		tNombre = (TextView)findViewById(R.id.Nombre);
		tApellido = (TextView)findViewById(R.id.Apellido);
		tCiudad = (TextView)findViewById(R.id.Ciudad);
		
		rut = (EditText)findViewById(R.id.etRut);
		pass = (EditText)findViewById(R.id.etPAss);
		nombre = (EditText)findViewById(R.id.etNombre);
		apellido = (EditText)findViewById(R.id.etApellido);
		ciudad = (EditText)findViewById(R.id.etCiudad);
		
		registrar = (Button)findViewById(R.id.button1);
		
		registrar.setOnClickListener(new OnClickListener() {
	        
			@Override
			public void onClick(View arg0) {
				
				new addCliente().execute(rut.getText().toString(), pass.getText().toString(), 
						nombre.getText().toString(), apellido.getText().toString(),
						ciudad.getText().toString());     
				
				
			}});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.registro, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	class addCliente extends AsyncTask<String, Void, String> {
		private static final String TAG = "agregarCliente";
		ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(Registro.this, "Cargando...",
					"Agregando Cliente", true, true);

		}

		@Override
		protected String doInBackground(String... params) {
			String run = params[0];
			String pass = params[1];
			String name = params[2];
			String lname = params[3];
			String city = params[4];

			String result = "";

			try {

				PersonaVO personaVO = new PersonaVO(run, pass, name, lname,
						city);
				result = registrarUsuario(personaVO);

				Log.i(TAG, result);

			} catch (Exception e) {
				Log.e(TAG, e.getCause().toString());
			}

			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();

			if ("".equals(result)) {
				Toast.makeText(Registro.this,
						"Existe problemas de conectividad con el servidor",
						Toast.LENGTH_SHORT).show();
			} else if (result.contains("Error")) {
				Toast.makeText(getApplicationContext(), result,
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(getApplicationContext(), result,
						Toast.LENGTH_LONG).show();
				Intent i = new Intent(Registro.this, Principal.class);
				startActivity(i);

			}

		}
 }
	
	public String registrarUsuario(PersonaVO oPersonaVO) {
        
        String method = "registrarPersona";
        String TAG = method;
        Log.i("intentando enviar datos al ws usando: ", method);

              try{  
                String SOAP_ACTION = util.Constantes.NAMESPACE+"#"+method;
                System.out.println(SOAP_ACTION);
                SoapObject request = new SoapObject(util.Constantes.NAMESPACE, method);

                Gson gson = new Gson();
                String persona = gson.toJson(oPersonaVO);
                System.out.println(persona);
                        request.addProperty("json",persona);
                
             
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
                envelope.setOutputSoapObject(request);
                
                envelope.addMapping(util.Constantes.NAMESPACE, "PersonaVO", new PersonaVO().getClass());

                HttpTransportSE transporte = new HttpTransportSE(util.Constantes.URL);
                transporte.debug = true;

                transporte.call(SOAP_ACTION, envelope);
              
                Log.i(TAG, "dump Request: "+ transporte.requestDump);
                        Log.i(TAG, "dump Response: "+ transporte.responseDump);
                        
                Vector response =(Vector)envelope.getResponse();
                String res = (String)response.get(1);
                        
                        return res;
                        
                }catch (Exception e) 
                {
                       e.printStackTrace();
                       
                }  
 
  return null;
  }
}
